import React from 'react'


import {Dimensions, Image, StyleSheet, Text, TextInput, TouchableOpacity, View, Alert} from 'react-native';
import BasePage from './Component/Common/BasePage';
import PageView from './Component/Common/PageView'
import {Button} from 'teaset';
import CommonStyle from "./Component/CommonStyle";

import {Theme, NavigationPage, ListRow, NavigationBar, Label} from 'teaset';
import SQLite from './SQLite';
import MyPage from "./MyPage";

var sqLite = new SQLite();
var db;

let screenW = Dimensions.get('window').width;
let screenH = Dimensions.get('window').height;
export default class FindPasswordPage extends BasePage {


    constructor(props) {

        super(props);

        this._onChangeText = this._onChangeText.bind(this);
        this._onChangeTexttwo = this._onChangeTexttwo.bind(this);
        this.state = {
            ...this.state,
            name: '',
            password: '',
            newpassword: '',
            imgData: [
                {
                    url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1539232796910&di=a31f022f38a309f19bc24350b0a24835&imgtype=0&src=http%3A%2F%2Fwww.tcyyy.cn%2Fd%2Ffile%2FTech%2F2018-01-19%2Fca9893d011335a1ddee140b0665e9ff5.jpg',
                    "direaction": 1,

                },
                {
                    url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1539232796908&di=67b60d06e112f3548de50bb0cbec61cf&imgtype=0&src=http%3A%2F%2Fimg.shushi100.com%2F2017%2F12%2F08%2F1512704163-4960912661779183.png',
                    "direaction": 3
                }
                ,
                {
                    url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1539232894554&di=677351959e34802f29a9fe6dfe5af3a4&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201512%2F12%2F20151212120309_BduTC.jpeg',
                    "direaction": 2
                }
                ,
                {
                    url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1539233087294&di=69a821dea99c5a0bc82802bf9485d38e&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F00%2F93%2F81%2F4956f2ad485645b.jpg',
                    "direaction": 4
                }
            ],
            po: 0
        };

    }

    componentWillMount() {
        //开启数据库
        if (!db) {
            db = sqLite.open();
        } else {
            //建表
            sqLite.createTable();
        }


    }


    changeDireaction(direaction) {

        var dirc = ""
        if (direaction == 1) {
            dirc = [{
                rotate: "0deg"
            }]
        } else if (direaction == 2) {
            dirc = [{
                rotate: "90deg"
            }]
        }
        else if (direaction == 3) {
            dirc = [{
                rotate: "180deg"
            }]
        }
        else if (direaction == 4) {
            dirc = [{
                rotate: "270deg"
            }]
        }
        return dirc
    }


    componentDidMount() {
    }


    _onChangeText(inputData) {

        this.setState({
            name: inputData
        })
    }

    _onChangeTexttwo(inputData) {

        this.setState({
            password: inputData
        })
    }


    _onChangeTextthree(aa) {

        this.setState({
            newpassword: aa
        })

    }

    //
    // //读取数据
    // _readData = () => {
    //     storage.load({
    //         key: 'loginState', // autoSync(默认为true)意味着在没有找到数据或数据过期时自动调用相应的sync方法
    //         autoSync: true, // syncInBackground(默认为true)意味着如果数据过期， // 在调用sync方法的同时先返回已经过期的数据。
    //         // 设置为false的话，则等待sync方法提供的最新数据(当然会需要更多时间)。
    //         syncInBackground: true, // 你还可以给sync方法传递额外的参数
    //         syncParams: {
    //             extraFetchOptions: { // 各种参数
    //             },
    //             someFlag: true,
    //         },
    //     }).then(ret => {
    //
    //
    //         // 如果找到数据，则在then方法中返回 // 注意：这是异步返回的结果（不了解异步请自行搜索学习）
    //         // 你只能在then这个方法内继续处理ret数据 // 而不能在then以外处理 // 也没有办法“变成”同步返回
    //         // 你也可以使用“看似”同步的async/await语法
    //         console.log(ret.name);
    //         this.setState({data: ret.name});
    //     }).catch(err => { //如果没有找到数据且没有sync方法， //或者有其他异常，则在catch中返回
    //         console.warn(err.message);
    //         switch (err.name) {
    //             case 'NotFoundError':
    //                 // TODO;
    //                 this.setState({data: 'NotFoundError'});
    //                 break;
    //             case 'ExpiredError':
    //                 this.setState({data: 'ExpiredError'});
    //                 break;
    //         }
    //     })
    //
    //
    // }

    renderNavigationBar() {
        return (
            <NavigationBar
                style={{backgroundColor: '#1196DB',}}

                title={
                    <View style={{
                        flexDirection: 'row',
                        justifyContent: 'center',
                        alignSelf: 'center',

                    }}>
                        <Text style={{
                            fontSize: 20,
                            color: '#ffffff'
                        }}>找回密码</Text>
                    </View>}
                leftView={<TouchableOpacity
                    onPress={() => {
                        this.navigator.pop();

                    }}
                >
                    <Image style={{width: 15, height: 15, marginLeft: 20}} source={require('./images/btn_back.png')}/>

                </TouchableOpacity>}
            />
        );
    }

    renderPage() {
        return (
            <View style={{flex: 1, marginTop: 80}} hiddenNav={true} fromPage={this} {...this.state}>

                <View style={{
                    flexDirection: 'column',
                    flex: 1
                }}>

                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        height: 40,
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginRight: 15,
                        borderWidth: 1,
                        borderRadius: 5,
                        borderColor: '#d9d9d9'
                    }}>
                        <TextInput
                            underlineColorAndroid='transparent'
                            placeholder="请输入用户名"
                            editable={true}//是否可编辑
                            style={styles.inputStyle}//input框的基本样式
                            onChangeText={this._onChangeText}//输入框改变触发的函数

                        />

                    </View>

                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        marginTop: 10,
                        height: 40,
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginRight: 15,
                        borderWidth: 1,
                        borderRadius: 5,
                        borderColor: '#d9d9d9'
                    }}>

                        <TextInput
                            underlineColorAndroid='transparent'
                            placeholder="请旧输入密码"
                            editable={true}//是否可编辑
                            style={styles.inputStyle}//input框的基本样式
                            onChangeText={this._onChangeTexttwo}//输入框改变触发的函数
                        />
                    </View>
                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        marginTop: 10,
                        height: 40,
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginRight: 15,
                        borderWidth: 1,
                        borderRadius: 5,
                        borderColor: '#d9d9d9'
                    }}>

                        <TextInput
                            underlineColorAndroid='transparent'
                            placeholder="请新输入密码"
                            editable={true}//是否可编辑
                            style={styles.inputStyle}//input框的基本样式
                            onChangeText={(text) => {
                                this.setState({
                                    newpassword: text
                                })
                            }}//输入框改变触发的函数
                        />
                    </View>
                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        marginTop: 10,
                        height: 40,
                        flexDirection: 'row',
                        alignItems: 'center',

                    }}>
                        <Text>将图片旋转到正确的方向验证</Text>

                    </View>

                    <View style={{
                        marginRight: 15,
                        marginLeft: 15,
                        marginTop: 10,
                        height: 90,
                        flexDirection: 'row',
                        alignItems: 'center',

                    }}>

                        <TouchableOpacity
                            onPress={() => {

                                this.state.imgData[0].direaction = this.state.imgData[0].direaction >= 3 ? 1 : this.state.imgData[0].direaction + 1;
                                this.setState(
                                    {
                                        imgData: this.state.imgData
                                    }
                                );
                            }}


                            activeOpacity={1} key={0}
                        >
                            <Image source={{
                                uri: this.state.imgData[0].url
                            }}
                                   style={{
                                       width: screenW / 5 - 5,
                                       height: screenW / 5 - 5,
                                       marginLeft: 10,
                                       transform: this.changeDireaction(this.state.imgData[0].direaction)
                                   }}

                                   resizeMode={'cover'}
                            >


                            </Image>

                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => {

                                this.state.imgData[1].direaction = this.state.imgData[1].direaction >= 3 ? 1 : this.state.imgData[1].direaction + 1;
                                this.setState(
                                    {
                                        imgData: this.state.imgData
                                    }
                                );
                            }}


                            activeOpacity={1} key={1}
                        >
                            <Image source={{
                                uri: this.state.imgData[1].url
                            }}
                                   style={{
                                       width: screenW / 5 - 5,
                                       height: screenW / 5 - 5,
                                       marginLeft: 10,
                                       transform: this.changeDireaction(this.state.imgData[1].direaction)
                                   }}

                                   resizeMode={'cover'}
                            >


                            </Image>

                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => {

                                this.state.imgData[2].direaction = this.state.imgData[2].direaction >= 3 ? 1 : this.state.imgData[2].direaction + 1;
                                this.setState(
                                    {
                                        imgData: this.state.imgData
                                    }
                                );
                            }}


                            activeOpacity={1} key={2}
                        >
                            <Image source={{
                                uri: this.state.imgData[2].url
                            }}
                                   style={{
                                       width: screenW / 5 - 5,
                                       height: screenW / 5 - 5,
                                       marginLeft: 10,
                                       transform: this.changeDireaction(this.state.imgData[2].direaction)
                                   }}

                                   resizeMode={'cover'}
                            >


                            </Image>

                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => {

                                this.state.imgData[3].direaction = this.state.imgData[3].direaction >= 3 ? 1 : this.state.imgData[3].direaction + 1;
                                this.setState(
                                    {
                                        imgData: this.state.imgData
                                    }
                                );
                            }}


                            activeOpacity={1} key={3}
                        >
                            <Image source={{
                                uri: this.state.imgData[3].url
                            }}
                                   style={{
                                       width: screenW / 5 - 5,
                                       height: screenW / 5 - 5,
                                       marginLeft: 10,
                                       transform: this.changeDireaction(this.state.imgData[3].direaction)
                                   }}

                                   resizeMode={'cover'}
                            >

                            </Image>

                        </TouchableOpacity>
                    </View>

                    <View style={{marginRight: 15, marginLeft: 15, marginTop: 40, height: 50}}>
                        <Button
                            title="确    认"
                            style={{flex: 1}}
                            onPress={() => this.add()}
                            color="#1196DB">
                        </Button>
                    </View>
                </View>

            </View>
        );

    }

    componentDidMount() {

    }

    add() {
        var istur = false;


        if (istur) {
            alert('验证错误')
            return
        }
        if (this.state.password == '') {
            alert('请输入密码')
            return
        }
        if (this.state.newpassword == '') {
            alert('请输入密码')
            return
        }

        for (var i = 0; i < this.state.imgData.length; i++) {
            if (this.state.imgData[i].direaction != 1) {
                istur = true
            }

        }


        //查询
        db.transaction((tx) => {
            tx.executeSql("select * from user  WHERE name=? ", [this.state.name], (tx, results) => {
                var len = results.rows.length;


                for (let i = 0; i < len; i++) {
                    var u = results.rows.item(i);
                    if (u.name == this.state.name) {

                        if (u.password == this.state.password) {

                            var updateDataSQL = 'UPDATE  USER' + ' SET PASSWORD = ? WHERE NAME = ?';
                            var onepassword = this.state.newpassword;
                            var onename = this.state.name;
                            db.transaction(function (context) {
                                    context.executeSql(updateDataSQL, [onepassword, onename]);
                                },
                                function (error) {
                                    alert('更新数据失败' + error.message)
                                }, function () {
                                    console.log('更新数据成功');
                                    alert('更新数据成功')
                                });


                        }
                    }

                    //一般在数据查出来之后，  可能要 setState操作，重新渲染页面
                }

            });
        }, (error) => {//打印异常信息
        });

        // //模拟一条数据
        // var userData = [];
        // var user = {};
        // user.name = this.state.name;
        // user.age = "";
        // user.sex = "";
        // user.password = this.state.password;
        // user.headurl = "";
        // user.qq = "";
        // userData.push(user);
        // //插入数据
        // sqLite.insertUserData(userData);
        //
        // alert('注册成功，返回登录')
    }

}
const
    styles = StyleSheet.create({

        button2: {
            height: 29,
            width: CommonStyle.screenwidth / 5,
            flexDirection: 'row',
            borderTopRightRadius: 5,
            borderBottomRightRadius: 5,
        }, inputStyle: {

            flex: 1,
            marginLeft: 10,
        }
    });
